package com.xunyin.modules.coupon.rest;


import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xunyin.api.ApiResult;
import com.xunyin.api.XunyinException;
import com.xunyin.common.dto.ParamDto;
import com.xunyin.constant.Constants;
import com.xunyin.enums.TimeScaleEnum;
import com.xunyin.enums.WeekDayEnum;
import com.xunyin.modules.couponnew.domain.MtCoupon;
import com.xunyin.modules.couponnew.service.CouponService;
import com.xunyin.modules.couponnew.service.dto.ReqCouponDto;
import com.xunyin.modules.log.AppLog;
import com.xunyin.modules.mtstore.service.mapper.MtStoreRoomMapper;
import com.xunyin.modules.mtstore.vo.MtStoreRoomVo;
import com.xunyin.modules.user.domain.YxUser;
import com.xunyin.modules.user.service.mapper.UserMapper;
import com.xunyin.pagination.PaginationRequest;
import com.xunyin.pagination.PaginationResponse;
import com.xunyin.utils.PhoneFormatCheckUtils;
import com.xunyin.web.ResponseObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 卡券接口controller
 * <p>
 * Created by xunyinyunshang <3594419785@qq.com>
 * CopyRight 讯音云商 https://www.tonetn.com
 */
@Slf4j
@RestController
@Api(value = "卡券接口相关", tags = "共享空间:卡券接口相关")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class ClientCouponController {

    /**
     * 卡券服务接口
     */
    private final CouponService couponService;

    private final MtStoreRoomMapper mtStoreRoomMapper;

    private final UserMapper yxUserMapper;


    /**
     * 获取卡券列表数据
     */
    @AppLog(value = "获取卡券列表", type = 1)
    //@AuthCheck
    @PostMapping("/coupon/list")
    @ApiOperation(value = "获取卡券列表", notes = "获取卡券列表")
    public ApiResult<Map<String, Object>> getCouponList(HttpServletRequest request, @RequestBody Map<String, Object> param) {
/*        String token = request.getHeader("Access-Token");
        UserInfo mtUser = TokenUtil.getUserInfoByToken(token);
        if (null != mtUser) {
            param.put("userId", mtUser.getId());
        }*/

        Map<String, Object> data = new HashMap();
        ResponseObject couponData = couponService.findCouponList(param);
        data.put("couponList", couponData.getData());

        return ApiResult.ok(data);
    }


    /**
     * 获取可用星期、可用时间段、适用房间
     */
    @AppLog(value = "获取可用星期、可用时间段、适用房间", type = 1)
    //@AuthCheck
    @PostMapping("/coupon/baseList")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "key", value = "唯一的key", paramType = "query", dataType = "string")
    })
    @ApiOperation(value = "获取可用星期、可用时间段、适用房间", notes = "获取可用星期、可用时间段、适用房间")
    public ApiResult<Map<String, Object>> getCouponBaseList(@RequestBody Map<String, Object> param) {

        Integer storeId = (param.get("storeId") == null) ? 0 : Integer.parseInt(param.get("storeId").toString());
        List<MtStoreRoomVo> storeRoomList = mtStoreRoomMapper.getStoreRoomList(storeId);
        for(MtStoreRoomVo mtStoreRoomVo :storeRoomList){
            mtStoreRoomVo.setChecked(false);
        }

        // 星期列表
        WeekDayEnum[] weekDayEnum = WeekDayEnum.values();
        List<ParamDto> weekDayForList = new ArrayList<>();
        for (WeekDayEnum enumItem : weekDayEnum) {
            ParamDto paramDto = new ParamDto();
            paramDto.setKey(enumItem.getKey());
            paramDto.setName(enumItem.getValue());
            paramDto.setValue(enumItem.getKey());
            weekDayForList.add(paramDto);
        }

        // 时间段列表
        TimeScaleEnum[] timeScaleEnum = TimeScaleEnum.values();
        List<ParamDto> timeScaleForList = new ArrayList<>();
        for (TimeScaleEnum enumItem : timeScaleEnum) {
            ParamDto paramDto = new ParamDto();
            paramDto.setKey(enumItem.getKey());
            paramDto.setName(enumItem.getValue());
            paramDto.setValue(enumItem.getKey());
            timeScaleForList.add(paramDto);
        }

        Map<String, Object> result = new HashMap<>();
        result.put("weekDayForList", weekDayForList);
        result.put("timeScaleForList", timeScaleForList);
        result.put("storeRoomList", storeRoomList);
        return ApiResult.ok(result);
    }


    /**
     * 新增、修改卡券接口
     *
     * @return ApiResult<String>
     */
    @AppLog(value = "新增、修改卡券接口", type = 1)
    //@AuthCheck
    @PostMapping("/coupon/save")
    @ApiOperation(value = "新增、修改卡券接口", notes = "新增、修改卡券接口")
    public  ApiResult<String> saveCoupon(HttpServletRequest request, @RequestBody ReqCouponDto reqCouponDto) {
        reqCouponDto.setOperator("门店小程序管理者");
        // 同一分组内卡券名称不能重复
        PaginationRequest requestSearch = new PaginationRequest();
        requestSearch.setCurrentPage(Constants.PAGE_NUMBER);
        requestSearch.setPageSize(Constants.PAGE_SIZE);
        Map<String, Object> requestParams = new HashMap<>();
        requestParams.put("name", reqCouponDto.getName());
        //requestParams.put("groupId", reqCouponDto.getGroupId().toString());
        requestSearch.setSearchParams(requestParams);
        PaginationResponse<MtCoupon> dataName = couponService.queryCouponListByPagination(requestSearch);
        if (dataName.getContent().size() > 0 && reqCouponDto.getId() == null) {

            return ApiResult.ok("").setMsg("卡券名称已存在，请修改");
            //throw new XunyinException("卡券名称已存在，请修改");
            //return getFailureResult(201, "卡券名称已存在，请修改");
        }

        try {
            couponService.saveCoupon(reqCouponDto);
        } catch (ParseException e) {
            throw new XunyinException(e.getMessage());
            //return getFailureResult(201, e.getMessage());
        }

        return ApiResult.ok("").setMsg("保存成功");
    }


    /**
     * 发放卡券接口
     *
     * @return ApiResult<String>
     */
    @AppLog(value = "发放卡券接口", type = 1)
    //@AuthCheck
    @PostMapping("/coupon/sendCoupon")
    @ApiOperation(value = "发放卡券接口", notes = "发放卡券接口")
    public ApiResult<String> sendCoupon(HttpServletRequest request, @RequestBody ReqCouponDto reqCouponDto) {
/*        String mobile = request.getParameter("mobile");
        String num = request.getParameter("num");
        String couponId = request.getParameter("couponId");
        String storeId = request.getParameter("storeId");*/

        if (reqCouponDto.getId() == null) {
            //throw new XunyinException("系统参数有误");
            return ApiResult.ok("").setMsg("系统参数有误");
        }

        if (!PhoneFormatCheckUtils.isChinaPhoneLegal(reqCouponDto.getMobile())) {
            return ApiResult.ok("").setMsg("手机号格式有误");
            //throw new XunyinException("手机号格式有误");

        }

        Pattern pattern = Pattern.compile("[1-9]\\d*");
        if (reqCouponDto.getSendNum() == null || (!pattern.matcher(reqCouponDto.getSendNum()+"").matches())) {
            return ApiResult.ok("").setMsg("发放数量必须为大于零的正整数");
            //throw new XunyinException("发放数量必须为正整数");
        }

        YxUser user = yxUserMapper.selectOne((Wrappers.<YxUser>lambdaQuery().eq(YxUser::getUsername, reqCouponDto.getMobile())));
        if (user == null) {
            return ApiResult.ok("").setMsg("输入手机号没有对应的用户");
            //throw new XunyinException("输入手机号没有对应的用户");
        }


        couponService.sendCoupon(reqCouponDto.getId(), reqCouponDto.getSendNum() , user.getUid().intValue(), reqCouponDto.getStoreId());
        //couponService.sendCoupon(Integer.parseInt(couponId), Integer.parseInt(num), user.getUid().intValue(), Integer.parseInt(storeId));

        return ApiResult.ok("").setMsg("发放成功");
        //return new ResponseEntity(HttpStatus.OK);

    }

    /**
     * 更新卡券（小时卡、次卡、优惠券）是否新注册用户赠送，0：表示否 1：表示是 接口
     *
     * @return ApiResult<String>
     */
    @AppLog(value = "更新卡券（小时卡、次卡、优惠券）是否新注册用户赠送，A：是；D：否 接口", type = 1)
    //@AuthCheck
    @PostMapping("/coupon/updateIsNewGiveStatus")
    @ApiOperation(value = "更新卡券（小时卡、次卡、优惠券）是否新注册用户赠送，A：是；D：否 接口", notes = "更新卡券（小时卡、次卡、优惠券）是否新注册用户赠送，A：是；D：否 接口")
    public ApiResult<String> updateIsNewGiveStatus(HttpServletRequest request, @RequestBody ReqCouponDto reqCouponDto) {

        //String roomOnlineStatus = params.get("roomOnlineStatus") != null ? params.get("roomOnlineStatus").toString() : StatusEnum.ENABLED.getKey();
        //Integer roomId = params.get("roomId") == null ? 0 : Integer.parseInt(params.get("roomId").toString());
        couponService.updateIsNewGiveStatus(reqCouponDto.getId(), reqCouponDto.getIsNewGive());
        //mtStoreRoomService.updateRoomOnlineStatus(resources.getId(), resources.getRoomOnlineStatus());



        return ApiResult.ok("").setMsg("更新卡券赠送状态成功");
    }

    /**
     * 根据条件查询卡券
     *
     */
    @AppLog(value = "根据条件查询卡券", type = 1)
    //@AuthCheck
    @PostMapping("/queryCouponListByCondi")
    @ApiOperation(value = "queryCouponListByCondi", notes = "根据条件查询卡券")
    public ApiResult<List<MtCoupon>> queryCouponListByCondi(@Validated @RequestBody MtCoupon coupon) {
        //Long uid = LocalUser.getUser().getUid();
        List<MtCoupon> list = couponService.queryCouponListByCondi(coupon);
        return ApiResult.ok(list);
    }

/*    *//**
     * 管理员获取门店卡券列表数据
     *//*
    @AppLog(value = "管理员获取门店卡券列表数据", type = 1)
    //@AuthCheck
    @PostMapping("/coupon/storeList")
    @ApiOperation(value = "管理员获取门店卡券列表数据", notes = "管理员获取门店卡券列表数据")
    public ApiResult<Map<String, Object>> getStoreCouponList(HttpServletRequest request, @RequestBody Map<String, Object> param) {

    }*/




}


